package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.data.RespCodeEnum;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.data.ResultCodeEnum;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.DesensitizationUtils;
import com.yx.changdao.common.utils.ExcelImportExportUtils;
import com.yx.changdao.common.utils.SysConst;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.common.vo.BuildBuildVo;
import com.yx.changdao.service.*;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: <br/>
 * 网格信息库表
 * <p>
 * <br/>
 * @Auther: walter
 * @create 2020/04/02 14:20
 */
@Validated
@RestController
@RequestMapping("grid/info")
public class GridInfoController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 网格信息库表服务
     */
    @Autowired
    private GridInfoService gridInfoService;
    /**
     * 社区建筑物表服务
     */
    @Autowired
    private CommunityBuildService communityBuildService;

    @Autowired
    private CommunityResidentService communityResidentService;
    /**
     * 建筑物联户组关联服务
     */
    @Autowired
    private ContactGroupBuildService contactGroupBuildService;

    /**
     * 列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
    public Result list(@RequestParam(value = "page") Long page,
                       @RequestParam(value = "limit", required = false) Integer limit) throws AlertException {
        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        if (page == null) {
            page = 1L;
        }
        /**
         * 分页配置
         */
        Page<GridInfo> pager = new Page<>(page, limit);
        /**
         * 根据条件查询出集合
         */
        QueryWrapper<GridInfo> queryWrapper = SysUtils.autoCnd(GridInfo.class);
        // 获取分页结果集。
        IPage<GridInfo> departmentPage = this.gridInfoService.page(pager, queryWrapper.orderByDesc(GridInfo.CREATE_TIME));
        List<GridInfo> list = departmentPage.getRecords();
      /*  if (list != null) {
            //求区的实际楼房数
            for (GridInfo gridInfo : list) {
                gridInfo.setCountBuildNumber(0);
                List<CommunityRegion> byGridinfoId = communityRegionService.getByGridinfoId(gridInfo.getId());
                if (byGridinfoId == null) {
                    gridInfo.setCountBuildNumber(0);
                } else {
                    for (CommunityRegion communityRegion : byGridinfoId) {
                        List<CommunityBuild> buildByRegionId = communityBuildService.getBuildByRegionId(communityRegion.getId());
                        gridInfo.setCountBuildNumber(gridInfo.getCountBuildNumber() + buildByRegionId.size());
                    }
                }

            }
        }*/
        Map<String, Object> map = new HashMap();
        map.put("list", list);
        map.put("pager", departmentPage);
        return Result.ok().data(map);
    }


    /**
     * 添加网格信息库表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
    public Result add(@RequestBody @Valid GridInfo gridInfo) throws AlertException {
        GridInfo one = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.GRID_NUM, gridInfo.getGridNum()));
        if (one != null) {
            throw new AlertException("该网格编号已存在");
        }
        GridInfo gridInfoServiceOne = gridInfoService.getOne(new QueryWrapper<GridInfo>()
                .eq(GridInfo.GRID_NAME, gridInfo.getGridName())
                .eq(GridInfo.VILLAGE_ID, gridInfo.getVillageId()));
        if (gridInfoServiceOne != null) {
            throw new AlertException(gridInfo.getGridName() + " 网格已存在");
        }
        if (Strings.isNotBlank(gridInfo.getGridmanPhone())) {
            boolean matches = gridInfo.getGridmanPhone().matches("^1[0-9]{10}$");
            if (matches == false) {
                throw new AlertException("请输入正确的网格员电话");
            }
        }
        if (Strings.isNotBlank(gridInfo.getGridemanCard())) {
            if (gridInfo.getGridemanCard().length() != 15 && gridInfo.getGridemanCard().length() != 18) {
                throw new AlertException("身份证不合法");
            }
        }
        boolean b = gridInfoService.save(gridInfo);
        if (!b) {
            throw new AlertException("添加失败");
        }

        GridInfo gridInfo1 = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.GRID_NUM, gridInfo.getGridNum()));
        BuildBuildVo buildBuildVo = new BuildBuildVo();
        buildBuildVo.setName(gridInfo1.getGridName());
        buildBuildVo.setId(gridInfo1.getId());
        return Result.ok("添加成功").data(buildBuildVo);
    }


    /**
     * 获得指定id 网格信息库表。
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id) throws AlertException {
        GridInfo gridInfo = gridInfoService.getById(id);
        gridInfo.setGridemanCard(DesensitizationUtils.idEncrypt(gridInfo.getGridemanCard()));
        /*gridInfo.setCountBuildNumber(0);
        List<CommunityRegion> byGridinfoId = communityRegionService.getByGridinfoId(gridInfo.getId());
        if (byGridinfoId == null) {
            gridInfo.setCountBuildNumber(0);
        } else {
            for (CommunityRegion communityRegion : byGridinfoId) {
                List<CommunityBuild> buildByRegionId = communityBuildService.getBuildByRegionId(communityRegion.getId());
                gridInfo.setCountBuildNumber(gridInfo.getCountBuildNumber() + buildByRegionId.size());
            }
        }*/
        if (gridInfo == null) {
            throw new AlertException("未找到相关网格信息");
        }

        return Result.ok().data(gridInfo);
    }


    /**
     * 更新网格信息库表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
    public Result update(@RequestBody @Valid GridInfo gridInfo) throws AlertException {
        GridInfo gridInfoServiceOne = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.ID, gridInfo.getId()));

        GridInfo one = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.GRID_NUM, gridInfo.getGridNum()));
        if (one != null && !one.getId().equals(gridInfo.getId())) {
            throw new AlertException("该网格编号已存在");
        }
        GridInfo gridInfo1 = gridInfoService.getOne(new QueryWrapper<GridInfo>()
                .eq(GridInfo.GRID_NAME, gridInfo.getGridName())
                .eq(GridInfo.VILLAGE_ID, gridInfoServiceOne.getVillageId()));
        if (gridInfo1 != null && !gridInfo1.getId().equals(gridInfo.getId())) {
            throw new AlertException("该网格名已存在");
        }
        if (Strings.isNotBlank(gridInfo.getGridmanPhone())) {
            boolean matches = gridInfo.getGridmanPhone().matches("^1[0-9]{10}$");
            if (matches == false) {
                throw new AlertException("请输入正确的网格员电话");
            }
        }
        if (Strings.isNotBlank(gridInfo.getGridemanCard())) {
            if (gridInfo.getGridemanCard().length() != 15 && gridInfo.getGridemanCard().length() != 18) {
                throw new AlertException("身份证不合法");
            }
        }
        boolean b = gridInfoService.updateById(gridInfo);
        if (!b) {
            throw new AlertException("更新失败");
        }
        List<CommunityResident> list = communityResidentService.list(new QueryWrapper<CommunityResident>().eq(CommunityResident.GRID_ID, gridInfo.getId()));
        if (list.size() != 0) {
            for (CommunityResident communityResident : list) {
                communityResident.setGridName(gridInfo.getGridName());
                communityResidentService.updateById(communityResident);
            }
        }


        return Result.ok("更新成功");
    }


    /**
     * 删除网格信息库表
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping("/{id}")
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public Result delete(@PathVariable("id") String id) throws AlertException {
        GridInfo one = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.ID, id));
        BuildBuildVo buildBuildVo = new BuildBuildVo();
        buildBuildVo.setId(one.getId());
        buildBuildVo.setName(one.getGridName());
//        boolean b1 = gridInfoService.removeRegion(Integer.parseInt(id));
//        if (!b1) {
//            throw new AlertException("删除失败");
//        }
        //查看网格下是否有楼信息
        List<CommunityBuild> list = communityBuildService.list(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.GRID_ID, id));
        if (list.size() != 0) {
            return new Result(RespCodeEnum.OK, null, ResultCodeEnum.DELETE, "您删除的层级内包含其他数据信息!", buildBuildVo);
        }
        //删除网格
        boolean b = gridInfoService.removeById(id);
        if (!b) {
            throw new AlertException("删除失败");
        }
        return Result.ok("删除成功").data(buildBuildVo);
    }


    /**
     * 查询有哪些网格部分也
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/listNopage")
    /*@RequiresPermissions("grid:info:list")
    @ShiroDesc("网格信息库表:下拉列表")*/
    public Result listNoPage() throws AlertException {
        /**
         * 根据条件查询出集合
         */
        QueryWrapper<GridInfo> queryWrapper = SysUtils.autoCnd(GridInfo.class);
        List<GridInfo> list = gridInfoService.list();
        List<BuildBuildVo> list1 = new ArrayList<>();
        for (GridInfo gridInfo : list) {
            BuildBuildVo buildBuildVo = new BuildBuildVo();
            buildBuildVo.setId(gridInfo.getId());
            buildBuildVo.setName(gridInfo.getGridName());
            list1.add(buildBuildVo);
        }
        Map<String, Object> map = new HashMap();
        map.put("list", list1);
        return Result.ok().data(map);
    }


    /**
     * 执行部门网格显示
     */
    @AutoLog
    @GetMapping("/listExecute")
    public Result listExecute() throws AlertException {
        String userId = SysUtils.currentUserId();
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
        if (sysUser == null) {
            return Result.error("该帐号不存在");
        }
        List<BuildBuildVo> list1 = new ArrayList<>();
        //获取这个小组关联的楼
        List<ContactGroupBuild> contactGroupBuilds = contactGroupBuildService.list(new QueryWrapper<ContactGroupBuild>()
                .eq(ContactGroupBuild.CONTACT_GROUP_ID, sysUser.getContactGroupId()));
        if (contactGroupBuilds.size() == 0) {
            return Result.ok().data(list1);
        }
        Integer[] gridId = new Integer[contactGroupBuilds.size()];
        for (int i = 0; i < contactGroupBuilds.size(); i++) {
            CommunityBuild communityBuild = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.ID, contactGroupBuilds.get(i).getBuildId()));
            gridId[i]=communityBuild.getGridId();
        }

        List<GridInfo> list = gridInfoService.list(new QueryWrapper<GridInfo>().in(GridInfo.ID,gridId).orderByAsc(GridInfo.GRID_NUM));
        for (GridInfo gridInfo : list) {
           /* //查出这个部门的网格是否存在
            List<CommunityBuild> communityBuilds = communityBuildService.list(new QueryWrapper<CommunityBuild>()
                    .eq(CommunityBuild.GRID_ID, gridInfo.getId())
                    .eq(CommunityBuild.DEP_ID, sysUser.getDepId()));

            if (communityBuilds.size() == 0) {
                continue;
            }*/
            BuildBuildVo buildBuildVo = new BuildBuildVo();
            buildBuildVo.setId(gridInfo.getId());
            buildBuildVo.setName(gridInfo.getGridName());
            list1.add(buildBuildVo);
        }
        return Result.ok().data(list1);
    }


    /**
     * 根据村id查网格
     */
    @AutoLog
    @GetMapping("/getGridByVillageId")
    public Result getGridByVillageId(@RequestParam("villageId") Integer villageId) throws AlertException {
        List<GridInfo> list = gridInfoService.list(new QueryWrapper<GridInfo>()
                .eq(GridInfo.VILLAGE_ID, villageId)
                .orderByAsc(GridInfo.GRID_NUM));
        List<BuildBuildVo> buildBuildVoList = new ArrayList<>();
        for (GridInfo communityBuildDetail : list) {
            BuildBuildVo buildBuildVo = new BuildBuildVo();
            buildBuildVo.setId(communityBuildDetail.getId());
            buildBuildVo.setName(communityBuildDetail.getGridName());
            buildBuildVo.setParent_id(communityBuildDetail.getVillageId());
            buildBuildVoList.add(buildBuildVo);
        }
        return Result.ok().data(buildBuildVoList);
    }

    @AutoLog
    @GetMapping("/down")
    public void down() throws AlertException, IOException {
        HttpServletResponse response = SysUtils.getResponse();
        List<GridInfo> list = gridInfoService.list();
        ExcelImportExportUtils.writeExcel(GridInfo.class, list, response, "网格信息");
    }


}
